package com.umeox.watch.moto.launcher.ui.view;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.View;

import com.umeox.watch.moto.launcher.R;


public class SnowView extends View {
    private static final int NUM_SNOWFLAKES = 100;
    private static final int DELAY = 5;

    private SnowFlake[] snowflakes;
    private Paint mPaint;
    private Bitmap mBitmap1;
    private Bitmap mBitmap2;
    private Bitmap mBitmap3;
    private Bitmap mBitmap4;

    public SnowView(Context context) {
        this(context,null);
    }

    public SnowView(Context context, AttributeSet attrs) {
        this(context, attrs,0);
    }

    public SnowView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mPaint.setColor(Color.WHITE);
        mPaint.setStyle(Paint.Style.FILL);
        mBitmap1 = BitmapFactory.decodeResource(getResources(), R.drawable.snow_1);
        mBitmap2 = BitmapFactory.decodeResource(getResources(), R.drawable.snow_2);
        mBitmap3 = BitmapFactory.decodeResource(getResources(), R.drawable.snow_3);
        mBitmap4 = BitmapFactory.decodeResource(getResources(), R.drawable.snow_4);
    }

    protected void resize(int width, int height) {
        snowflakes = new SnowFlake[NUM_SNOWFLAKES];

        for (int i = 0; i < NUM_SNOWFLAKES; i++) {
            final SnowFlake snowFlake = SnowFlake.create(width, height, mPaint);
            if (i<=40) {
                snowFlake.setBitmap(mBitmap1);
                snowFlake.setIncrementSpeed(1.0f);
            }else if (i<=70){
                snowFlake.setBitmap(mBitmap2);
                snowFlake.setIncrementSpeed(1.0f);
            }else if (i<=90){
                snowFlake.setBitmap(mBitmap3);
                snowFlake.setIncrementSpeed(2.0f);
            }else{
                snowFlake.setBitmap(mBitmap4);
                snowFlake.setIncrementSpeed(2.0f);
            }

            snowflakes[i] = snowFlake;
        }
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        if (w != oldw || h != oldh) {
            resize(w, h);
        }
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        for (SnowFlake snowFlake : snowflakes) {
            snowFlake.draw(canvas);
        }
        getHandler().postDelayed(runnable, DELAY);
    }

    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            invalidate();
        }
    };
}
